<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件转换器</title>
  <style>
    :root {
      --primary-color: #4a6baf;
      --primary-hover: #3a5a9f;
      --secondary-color: #f8f9fa;
      --text-color: #333;
      --border-radius: 8px;
      --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      --transition: all 0.3s ease;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      color: var(--text-color);
    }
    
    .container {
      background-color: #ffffff;
      padding: 30px;
      border-radius: var(--border-radius);
      box-shadow: var(--box-shadow);
      text-align: center;
      max-width: 500px;
      width: 100%;
      transition: var(--transition);
    }
    
    h1 {
      margin-bottom: 30px;
      color: var(--primary-color);
      font-weight: 600;
      position: relative;
      padding-bottom: 10px;
    }
    
    h1:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 3px;
      background-color: var(--primary-color);
      border-radius: 3px;
    }
    
    .file-section {
      background-color: var(--secondary-color);
      padding: 20px;
      border-radius: var(--border-radius);
      margin-bottom: 20px;
      transition: var(--transition);
    }
    
    .file-section:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    label {
      display: block;
      margin-bottom: 10px;
      font-weight: 500;
      color: var(--primary-color);
    }
    
    input[type="file"] {
      margin: 10px 0;
      padding: 10px;
      width: 100%;
      border-radius: var(--border-radius);
      border: 1px solid #ddd;
      background-color: white;
      box-sizing: border-box;
    }
    
    button {
      margin: 10px 0;
      padding: 12px 20px;
      width: 100%;
      border-radius: var(--border-radius);
      background-color: var(--primary-color);
      color: white;
      border: none;
      cursor: pointer;
      font-weight: 500;
      transition: var(--transition);
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    
    button:hover {
      background-color: var(--primary-hover);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
    
    button:active {
      transform: translateY(0);
    }
    
    button:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }
    
    #message {
      margin-top: 20px;
      color: #555;
      background-color: var(--secondary-color);
      padding: 15px;
      border-radius: var(--border-radius);
      white-space: pre-line;
      min-height: 20px;
    }
    
    #progress {
      margin-top: 20px;
      width: 100%;
      background-color: #e9ecef;
      border-radius: 10px;
      overflow: hidden;
      height: 10px;
    }
    
    #progress-bar {
      width: 0%;
      height: 100%;
      background: linear-gradient(90deg, var(--primary-color), #6a8fd8);
      transition: width 0.3s ease;
      border-radius: 10px;
    }
    
    .error {
      color: #e74c3c;
      font-weight: 500;
    }
    
    .loading {
      display: none;
      margin: 20px auto;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      border: 4px solid rgba(74, 107, 175, 0.2);
      border-top-color: var(--primary-color);
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    
    /* 文件列表样式 */
    .file-list-section {
      margin-top: 30px;
      background-color: var(--secondary-color);
      padding: 20px;
      border-radius: var(--border-radius);
      text-align: left;
    }
    
    .file-list-section h2 {
      color: var(--primary-color);
      margin-bottom: 15px;
      text-align: center;
    }
    
    #file-list {
      margin-top: 15px;
      max-height: 300px;
      overflow-y: auto;
      border: 1px solid #ddd;
      border-radius: var(--border-radius);
      background-color: white;
    }
    
    .file-item {
      padding: 12px 15px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: var(--transition);
    }
    
    .file-item:last-child {
      border-bottom: none;
    }
    
    .file-item:hover {
      background-color: #f0f4f9;
    }
    
    .file-info {
      flex: 1;
    }
    
    .file-name {
      font-weight: 500;
      margin-bottom: 5px;
      color: var(--text-color);
    }
    
    .file-meta {
      font-size: 0.8rem;
      color: #777;
    }
    
    .download-btn {
      background-color: var(--primary-color);
      color: white;
      border: none;
      border-radius: 4px;
      padding: 6px 12px;
      cursor: pointer;
      transition: var(--transition);
    }
    
    .download-btn:hover {
      background-color: var(--primary-hover);
      transform: translateY(-2px);
    }
    
    .no-files {
      padding: 20px;
      text-align: center;
      color: #777;
    }
    
    @media (max-width: 600px) {
      .container {
        padding: 20px;
        margin: 0 15px;
      }
      
      .file-item {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .download-btn {
        margin-top: 10px;
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>文件转换器</h1>

    <div class="file-section">
      <label for="pdfInput">上传 PDF 文件：</label>
      <input type="file" id="pdfInput" accept=".pdf">
      <button id="pdfButton" onclick="uploadPdf()">转换 PDF</button>
    </div>

    <div class="file-section">
      <label for="wordInput">上传 Word 文件：</label>
      <input type="file" id="wordInput" accept=".docx">
      <button id="wordButton" onclick="uploadWord()">转换 Word</button>
    </div>

    <div id="progress">
      <div id="progress-bar"></div>
    </div>
    <div id="message"></div>
    <div class="loading" id="loading"></div>
    
    <div class="file-list-section" id="file-list-container">
      <h2>已转换文件列表</h2>
      <button id="refreshButton" onclick="loadFileList()">刷新列表</button>
      <div id="file-list"></div>
    </div>
  </div>

  <script>
    const API_URL = ""; // 使用相对路径
    let taskId = null;
    const loadingIndicator = document.getElementById('loading');

    // 页面加载完成后加载文件列表
    document.addEventListener('DOMContentLoaded', function() {
      loadFileList();
    });

    function disableButtons(disabled) {
      document.querySelectorAll("button").forEach(button => button.disabled = disabled);
    }

    function showLoading(isLoading) {
      loadingIndicator.style.display = isLoading ? 'block' : 'none';
    }
    
    // 加载文件列表
    function loadFileList() {
      const fileListContainer = document.getElementById('file-list');
      fileListContainer.innerHTML = '<div class="loading-text">加载文件列表中...</div>';
      
      fetch(`${API_URL}/files`)
        .then(response => response.json())
        .then(data => {
          if (data.files && data.files.length > 0) {
            fileListContainer.innerHTML = '';
            data.files.forEach(file => {
              // 格式化文件大小
              const fileSize = formatFileSize(file.size);
              // 格式化修改时间
              const modifiedTime = new Date(file.modified_time * 1000).toLocaleString();
              
              const fileItem = document.createElement('div');
              fileItem.className = 'file-item';
              fileItem.innerHTML = `
                <div class="file-info">
                  <div class="file-name">${file.filename}</div>
                  <div class="file-meta">大小: ${fileSize} | 修改时间: ${modifiedTime}</div>
                </div>
                <button class="download-btn" onclick="downloadFile('${file.filename}')">下载</button>
              `;
              fileListContainer.appendChild(fileItem);
            });
          } else {
            fileListContainer.innerHTML = '<div class="no-files">暂无已转换的文件</div>';
          }
        })
        .catch(error => {
          fileListContainer.innerHTML = `<div class="error">加载文件列表失败: ${error.message}</div>`;
        });
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
      if (bytes < 1024) {
        return bytes + ' B';
      } else if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(2) + ' KB';
      } else {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
      }
    }
    
    // 下载文件
    function downloadFile(filename) {
      fetch(`${API_URL}/download_file/${encodeURIComponent(filename)}`)
        .then(response => {
          if (response.status === 200) {
            // 获取 Content-Disposition 头部
            const contentDisposition = response.headers.get("Content-Disposition");
            let downloadFilename = filename;
            
            // 匹配 filename*=UTF-8'' 并解码文件名
            if (contentDisposition) {
              const utf8FilenameMatch = contentDisposition.match(/filename\*\=UTF\-8''(.+)/);
              if (utf8FilenameMatch && utf8FilenameMatch[1]) {
                downloadFilename = decodeURIComponent(utf8FilenameMatch[1]);
              }
            }
            
            return response.blob().then(blob => ({ blob, filename: downloadFilename }));
          } else {
            throw new Error("文件下载失败");
          }
        })
        .then(({ blob, filename }) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = filename.trim();
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        })
        .catch(error => {
          alert(`下载失败: ${error.message}`);
        });
    }

    function uploadPdf() {
      const fileInput = document.getElementById("pdfInput");
      const file = fileInput.files[0];

      if (!file) {
        document.getElementById("message").innerText = "请选择一个 PDF 文件上传。";
        document.getElementById("message").className = "error";
        return;
      }

      disableButtons(true);
      showLoading(true);

      const formData = new FormData();
      formData.append("file", file);

      document.getElementById("message").innerText = "上传并转换中...";
      document.getElementById("message").className = "";
      document.getElementById("progress-bar").style.width = "0%";

      fetch(`${API_URL}/convert`, {
        method: "POST",
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        disableButtons(false);
        showLoading(false);

        if (data.task_id) {
          taskId = data.task_id;
          document.getElementById("message").innerText = `任务已启动！任务 ID：${taskId}`;
          startCheckingProgress();
        } else {
          document.getElementById("message").innerText = `错误：${data.error || '未知错误'}`;
          document.getElementById("message").className = "error";
        }
      })
      .catch(error => {
        disableButtons(false);
        showLoading(false);
        document.getElementById("message").innerText = `错误：${error.message}`;
        document.getElementById("message").className = "error";
      });
    }

    function uploadWord() {
      const fileInput = document.getElementById("wordInput");
      const file = fileInput.files[0];

      if (!file) {
        document.getElementById("message").innerText = "请选择一个 Word 文件上传。";
        document.getElementById("message").className = "error";
        return;
      }

      disableButtons(true);
      showLoading(true);

      const formData = new FormData();
      formData.append("file", file);

      document.getElementById("message").innerText = "上传并转换中...";
      document.getElementById("message").className = "";
      document.getElementById("progress-bar").style.width = "0%";

      fetch(`${API_URL}/convert_word`, {
        method: "POST",
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        disableButtons(false);
        showLoading(false);

        if (data.task_id) {
          taskId = data.task_id;
          document.getElementById("message").innerText = `任务已启动！任务 ID：${taskId}`;
          startCheckingProgress();
        } else {
          document.getElementById("message").innerText = `错误：${data.error || '未知错误'}`;
          document.getElementById("message").className = "error";
        }
      })
      .catch(error => {
        disableButtons(false);
        showLoading(false);
        document.getElementById("message").innerText = `错误：${error.message}`;
        document.getElementById("message").className = "error";
      });
    }

    function startCheckingProgress() {
      const interval = setInterval(() => {
        if (taskId) {
          fetch(`${API_URL}/progress/${taskId}`)
            .then(response => response.json())
            .then(data => {
              if (data.progress) {
                document.getElementById("progress-bar").style.width = `${data.progress}%`;
                document.getElementById("message").innerText = data.message;
                if (data.progress === 100) {
                  document.getElementById("message").innerText += "\n任务完成，准备下载 Markdown 文件...";
                  clearInterval(interval);
                  downloadMarkdown();
                }
              }
            })
            .catch(error => {
              document.getElementById("message").innerText = `错误：${error.message}`;
              document.getElementById("message").className = "error";
              clearInterval(interval);
            });
        }
      }, 2000);
    }

    function downloadMarkdown() {
      fetch(`${API_URL}/download/${taskId}`)
        .then(response => {
          if (response.status === 200) {
            // 获取 Content-Disposition 头部
            const contentDisposition = response.headers.get("Content-Disposition");
            console.log("Content-Disposition Header:", contentDisposition);

            // 默认文件名
            let filename = 'default.md';

            // 匹配 filename*=UTF-8'' 并解码文件名
            if (contentDisposition) {
              const utf8FilenameMatch = contentDisposition.match(/filename\*\=UTF\-8''(.+)/);
              if (utf8FilenameMatch && utf8FilenameMatch[1]) {
                // 解码 UTF-8 编码的文件名
                filename = decodeURIComponent(utf8FilenameMatch[1]);
              }
            }

            console.log("Parsed filename:", filename);  // 输出解析的文件名

            return response.blob().then(blob => ({ blob, filename }));
          } else {
            throw new Error("任务未完成或任务 ID 无效。");
          }
        })
        .then(({ blob, filename }) => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = filename.trim();  // 使用解析出的文件名并去掉可能的空格
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          document.getElementById("message").innerText = "Markdown 文件已下载。";
          document.getElementById("message").className = "";
        })
        .catch(error => {
          document.getElementById("message").innerText = `错误：${error.message}`;
          document.getElementById("message").className = "error";
        });
    }
  </script>
</body>
</html>
